package engine

import (
	"code.google.com/p/go8/display"
	"code.google.com/p/go8/games"
	"github.com/gonutz/go-sdl2/sdl"
)

type Image interface {
	Size() (w, h int)
	DrawAt(pos display.Rect)
}

type MenuPainter interface {
	PaintMenu(game *games.Game) Image
}

type Centerer interface {
	Center(image Sizer, canvas CanvasSizer) display.Rect
}

type GameMenu struct {
	engine      GameEngine
	game        *games.Game
	menuPainter MenuPainter
	image       Image
	painter     display.Painter
	next        State
	previous    State
	gameState   State
	centerer    Centerer
}

func NewGameMenu(e GameEngine, g *games.Game, mp MenuPainter, p display.Painter) *GameMenu {
	return &GameMenu{engine: e, game: g, menuPainter: mp, painter: p}
}

func (menu *GameMenu) SetGameState(s State) {
	menu.gameState = s
}

func (menu *GameMenu) SetNextMenu(next State) {
	menu.next = next
}

func (menu *GameMenu) SetPreviousMenu(previous State) {
	menu.previous = previous
}

func (menu *GameMenu) SetCenterer(c Centerer) {
	menu.centerer = c
}

func (menu *GameMenu) Enter() {
	if menu.image == nil {
		menu.CreateMenuScreen()
	}
}

func (menu *GameMenu) CreateMenuScreen() {
	menu.image = menu.menuPainter.PaintMenu(menu.game)
}

func (menu *GameMenu) Exit() {}

func (menu *GameMenu) HandleEvent(e sdl.Event) {
	switch event := e.(type) {
	case *sdl.QuitEvent:
		menu.engine.Quit()
	case *sdl.KeyDownEvent:
		switch event.Keysym.Sym {
		case sdl.K_ESCAPE:
			menu.engine.Quit()
		case sdl.K_RETURN:
			menu.engine.ChangeState(menu.gameState)
		case sdl.K_LEFT:
			menu.engine.ChangeState(menu.previous)
		case sdl.K_RIGHT:
			menu.engine.ChangeState(menu.next)
		}
	}
}

func (menu *GameMenu) Draw() {
	menu.image.DrawAt(menu.centerer.Center(menu.image, menu.painter))
	menu.painter.Show()
}
